package com.jdd.modules.parkmonthly.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jdd.common.api.vo.Result;
import com.jdd.common.aspect.annotation.*;
import com.jdd.common.constant.JddConstant;
import com.jdd.common.system.query.QueryGenerator;
import com.jdd.common.system.vo.LoginUser;
import com.jdd.common.util.LoginUserUtils;
import com.jdd.modules.parking.entity.ParkInfo;
import com.jdd.modules.parking.service.IParkInfoService;
import com.jdd.modules.parkmonthly.entity.MonthlyCardInfo;
import com.jdd.modules.parkmonthly.entity.PermissionArea;
import com.jdd.modules.parkmonthly.entity.PermissionGroup;
import com.jdd.modules.parkmonthly.entity.PermissionGroupTreeModel;
import com.jdd.modules.parkmonthly.service.IMonthlyCardInfoService;
import com.jdd.modules.parkmonthly.service.IPermissionAreaService;
import com.jdd.modules.parkmonthly.service.IPermissionGroupService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

 /**
 * @Description: 权限组表
 * @Author: jdd
 * @Date:   2021-11-09
 * @Version: V1.0
 */
@Slf4j
@Api(tags="权限组表")
@RestController
@RequestMapping("/permissionGroup")
public class PermissionGroupController {

	@Resource
	private IPermissionGroupService permissionGroupService;
	@Resource
	private IPermissionAreaService permissionAreaService;
	 @Resource
	private IParkInfoService parkInfoService;
	 @Resource
	private IMonthlyCardInfoService monthlyCardInfoService;

	/**
	  * 分页列表查询
	 * @param permissionGroup
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "权限组表-分页列表查询")
	@ApiOperation(value="权限组表-分页列表查询", notes="权限组表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<PermissionGroup>> queryPageList(PermissionGroup permissionGroup,
														@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														HttpServletRequest req) {
		Result<IPage<PermissionGroup>> result = new Result<IPage<PermissionGroup>>();
		QueryWrapper<PermissionGroup> queryWrapper = QueryGenerator.initQueryWrapper(permissionGroup, req.getParameterMap());
		Page<PermissionGroup> page = new Page<PermissionGroup>(pageNo, pageSize);
		IPage<PermissionGroup> pageList = permissionGroupService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}


	 /**
	  * @Title: homePageParkList
	  * @Description:根据登录用户绑定车场组查询车场信息
	  * @return
	  * @author: zjf
	  * @date 2021年10月27日
	  * @version 1.0
	  */
	 @AutoLog(value = "停车场信息")
	 @ApiOperation(value = "停车场信息", notes = "停车场信息")
	 @GetMapping(value = "/permissionGroupList")
	 public Result<?> permissionGroupList() {
		 List<PermissionGroup> monthlyPackageInfoList = new ArrayList<PermissionGroup>();
			 QueryWrapper<PermissionGroup> queryWrapper = new QueryWrapper<>();
			// queryWrapper.eq("park_code",)
		 monthlyPackageInfoList = permissionGroupService.list();
		 return Result.ok(monthlyPackageInfoList);
	 }

	 /**
	  * 获取该车场的权限组，
	  * @return
	  */
	 @AutoLog(value = "权限组表-获取该车场的权限组")
	 @ApiOperation(value="权限组表-获取该车场的权限组", notes="权限组表-获取该车场的权限组")
	 @GetMapping(value = "/getPermissionGroup")
	 public Result<List<PermissionGroup>> getPermissionGroup() {
		 Result<List<PermissionGroup>> result = new Result<>();
		 List<PermissionGroup> permissionGroupList = permissionGroupService.list();
		 result.setResult(permissionGroupList);
		 result.setSuccess(true);
		 return result;
	 }


	 /**
	  * 获取该车场的权限组，树形结构
	  * @param parkCode
	  * @return
	  */
	 @AutoLog(value = "权限组表-获取该车场的权限组，树形结构")
	 @ApiOperation(value="权限组表-获取该车场的权限组，树形结构", notes="权限组表-获取该车场的权限组，树形结构")
	 @GetMapping(value = "/getParkPermissionGroup")
	 public Result<List<PermissionGroupTreeModel>> getParkPermissionGroup(@RequestParam(name = "parkCode",required = false) String parkCode,
																		  @RequestParam(name = "id",required = false) String id) {
		 Result<List<PermissionGroupTreeModel>> result = new Result<>();
		 List<PermissionGroup> permissionGroupList;
		 LambdaQueryWrapper<PermissionGroup> wrapper = new LambdaQueryWrapper<>();
		 if(StringUtils.isNotEmpty(id)){
			 wrapper.eq(PermissionGroup::getId, id);
		 }else {
		//	 wrapper.eq(PermissionGroup::getParkCode, parkCode);
			 wrapper.orderByAsc(PermissionGroup::getCreateTime);
		 }
		 permissionGroupList = permissionGroupService.list(wrapper);

		 List<PermissionGroupTreeModel> permissionGroupTreeData=new ArrayList<>();
		 for(PermissionGroup permissionGroup:permissionGroupList){
			 PermissionGroupTreeModel permissionGroupTreeModel=new PermissionGroupTreeModel();
			 BeanUtils.copyProperties(permissionGroup, permissionGroupTreeModel);
			 permissionGroupTreeModel.setKey(permissionGroup.getId());
			 permissionGroupTreeModel.setValue(permissionGroup.getId());
			 permissionGroupTreeModel.setTitle(permissionGroup.getPermissionName());
			 permissionGroupTreeModel.setChildren(new ArrayList<>());
			 permissionGroupTreeData.add(permissionGroupTreeModel);
		 }
		 result.setResult(permissionGroupTreeData);
		 result.setSuccess(true);
		 return result;
	 }


	 /**
	 /**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "权限组表-通过id查询")
	@ApiOperation(value="权限组表-通过id查询", notes="权限组表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<PermissionGroup> queryById(@RequestParam(name="id",required=true) String id) {
		Result<PermissionGroup> result = new Result<PermissionGroup>();
		PermissionGroup permissionGroup = permissionGroupService.getById(id);
		if(permissionGroup==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(permissionGroup);
			result.setSuccess(true);
		}
		return result;
	}

	 /**
	  *   添加
	  * @param permissionGroup
	  * @return
	  */
	 @AutoLog(value = "权限组表-添加")
	 @ApiOperation(value="权限组表-添加", notes="权限组表-添加")
	 @PostMapping(value = "/add")
	 @OperationLogDetail(detail ="添加权限组",level= LogLevelType.ONE,operationType = OperationType.INSERT,operationUnit = OperationUnit.UNKNOWN)
	 public Result<PermissionGroup> add(@RequestBody PermissionGroup permissionGroup) {
		 Result<PermissionGroup> result = new Result<PermissionGroup>();
		 try {
			 LoginUser loginUser = LoginUserUtils.getLoginUser();
			 if(null!=loginUser){
				 permissionGroup.setCreateUserId(loginUser.getUsername());
				 permissionGroup.setCreateUserName(loginUser.getRealname());
			 }
			 ParkInfo parkInfo=parkInfoService.getParkInfoByParkCode();
			 if(null==parkInfo){
				 result.error500("没有该车场信息");
			 }
			 permissionGroup.setCreateTime(new Date());
			 permissionGroup.setParkName(parkInfo.getParkName());
			 permissionGroupService.save(permissionGroup);
			 result.success("添加成功！");
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
			 result.error500("操作失败");
		 }
		 return result;
	 }

	 /**
	  * 编辑
	  *
	  * @param permissionGroup
	  * @return
	  */
	 @AutoLog(value = "权限-区域关联表-编辑")
	 @ApiOperation(value = "权限-区域关联表-编辑", notes = "权限-区域关联表-编辑")
	 @OperationLogDetail(detail ="编辑权限组",level= LogLevelType.ONE,operationType = OperationType.UPDATE,operationUnit = OperationUnit.UNKNOWN)
	 @PutMapping(value = "/edit")
	 public Result<PermissionGroup> edit(@RequestBody PermissionGroup permissionGroup) {
		 Result<PermissionGroup> result = new Result<>();
		 PermissionGroup permissionGroupEntity= permissionGroupService.getById(permissionGroup.getId());
		 if (permissionGroupEntity == null) {
			 result.error500("未找到对应实体");
		 } else {
			 permissionGroup.setUpdateTime(new Date());
			 LoginUser loginUser = LoginUserUtils.getLoginUser();
			 if(null!=loginUser){
				 permissionGroup.setUpdateUserId(loginUser.getUsername());
				 permissionGroup.setUpdateUserName(loginUser.getRealname());
			 }
			 boolean ok = permissionGroupService.updateById(permissionGroup);
			 //TODO 返回false说明什么？
			 if (ok) {
				 result.success("修改成功!");
			 }
		 }

		 return result;
	 }

	 /**
	  *   通过id删除
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "权限组表-通过id删除")
	 @ApiOperation(value="权限组表-通过id删除", notes="权限组表-通过id删除")
	 @DeleteMapping(value = "/delete")
	 @OperationLogDetail(detail ="删除权限组",level= LogLevelType.ONE,operationType = OperationType.DELETE,operationUnit = OperationUnit.UNKNOWN)
	 public Result<?> delete(@RequestParam(name="id",required=true) String id) {
	 	Result result=new Result();
		 try {
		 	//权限组下面如果关联了月租信息，则不允许删除
			 LambdaQueryWrapper<MonthlyCardInfo> wrapper=new LambdaQueryWrapper<>();
			 wrapper.eq(MonthlyCardInfo::getThroughAuthorityId,id);
			 wrapper.ne(MonthlyCardInfo::getMonthlyStatus, JddConstant.IntNumber.INT_THREE);
			 List<MonthlyCardInfo> list = monthlyCardInfoService.list(wrapper);
			 if(CollectionUtils.isNotEmpty(list)){
				 //关联了月租信息
				 result.error500("该权限组下关联了月租信息，不允许删除");
				 return result;
			 }
			 //权限组删除时关联的区域要删除
			 LambdaQueryWrapper<PermissionArea> permissionWrapper=new LambdaQueryWrapper<>();
			 permissionWrapper.eq(PermissionArea::getPermissionId,id);
			 permissionAreaService.remove(permissionWrapper);
			 //删除权限组
			 permissionGroupService.removeById(id);
		 } catch (Exception e) {
			 log.error("删除失败",e.getMessage());
			 return Result.error("删除失败!");
		 }
		 return Result.ok("删除成功!");
	 }
}
